#include "LinePlotter.h"

#include <vtkLookupTable.h>
#include <vtkPoints.h>
#include <vtkCellArray.h>
#include <vtkFloatArray.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkPointData.h>
#include <vtkProperty.h>

LinePlotter::LinePlotter():
	m_scalarMin(0.0),
	m_scalarMax(1.0),
	m_curPointID(0),
	m_allLineWidth(1)
{
	m_points = vtkPoints::New();
	m_lines = vtkCellArray::New();
	m_lineScalars = vtkFloatArray::New();
}

LinePlotter::~LinePlotter()
{
	m_points->Delete();
	m_lines->Delete();
	m_lineScalars->Delete();
}

void LinePlotter::SetScalarRange(double minval, double maxval)
{
	m_scalarMin = minval ;
	m_scalarMax = maxval ;
}

/*
	This method was changed so that it requires only half the amount of data of the original LinePlotter example.
	For each segment of a continueous line all inner points were stored twice : once for the first and once for the second line segment.
	Here a continueous line can be entered and each inner point serves 2 segments, thus requiring only half the amount of data.
*/
void LinePlotter::PlotLine(std::vector<Segment> &segments)
{
	m_lineScalars->SetNumberOfComponents(1);

	m_lines->InsertNextCell(segments.size());

	for(unsigned int i=0; i<segments.size(); i++)
	{
		m_points->InsertNextPoint(segments[i].point);
		
		m_lineScalars->InsertNextTuple1(segments[i].scalar);

		m_lines->InsertCellPoint(m_curPointID + i);
	}

	m_curPointID += segments.size();
}

void LinePlotter::SetAllLineWidth(int width)
{
	m_allLineWidth = width ;
}

vtkPolyData* LinePlotter::CreatePolyData()
{
	vtkPolyData* polyData = vtkPolyData::New();
	polyData->SetPoints(m_points);
	polyData->SetLines(m_lines);
	polyData->GetPointData()->SetScalars(m_lineScalars);

	return polyData;
}
vtkActor* LinePlotter::CreateActor()
{
	vtkPolyData* polyData = CreatePolyData();

	vtkPolyDataMapper* mapper = vtkPolyDataMapper::New();
	mapper->SetInput(polyData);
	mapper->SetLookupTable(vtkLookupTable::New());

	mapper->SetColorModeToMapScalars();
	mapper->SetScalarRange(m_scalarMin, m_scalarMax);
	mapper->SetScalarModeToUsePointData();

	vtkActor* actor = vtkActor::New();
	actor->SetMapper(mapper);
	actor->GetProperty()->SetLineWidth(m_allLineWidth);


	return actor ;	
}
